package com.anypi;

import java.io.IOException;

import com.tools.CRC;
import com.tools.Tools;

public class CybleReader{

	private final byte[] preamble = new byte[100];
	private CC1101 rfModule;
	private byte[] requestFrame = { 0x1D, 0x10, 0x00, 0x45, 0x0A, 0x07,			//default MIU: 11 0476898 (without CRC)
			0x46, (byte) 0xE2, 0x00, 0x45, 0x0C, 0x10, 0x50, 0x19, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00};
	
	private byte[] crc = new byte[2];

	public CybleReader(CC1101 radio, byte addr1, int addr2) throws InterruptedException, IOException {

		this.rfModule = radio;
		
		for (int i = 0; i < 100; i++) {
			preamble[i] = (byte) 0xAA;
		}
		
		setDestinationAdd(addr1, addr2);
	}
	
	public byte[] getRequestFrame() {
		return requestFrame;
	}
	
	public byte[] getCRC() {
		return crc;
	}
	
	
	
	public void setDestinationAdd(byte addr1, int addr2){
		
		requestFrame[4] = addr1;
		byte[] tmpAddr2 = Tools.intToBytes(addr2);
		
		requestFrame[5] = tmpAddr2[1];
		requestFrame[6] = tmpAddr2[2];
		requestFrame[7] = tmpAddr2[3];
		
		crc = CRC.calculate_crc_kermit(requestFrame);	//calculate the new CRC

	}
	
	//Send a request to the MIU, wait for the response and return the received frame (not decoded)
	public byte[] sendRequest() throws InterruptedException, IOException{
		
		rfModule.initRadio();
		byte[] frameToSend = new byte[requestFrame.length + 2];
		
		for(int i = 0; i < requestFrame.length; i++){
			frameToSend[i] = requestFrame[i];
		}
		
		frameToSend[frameToSend.length - 2] = crc[0];
		frameToSend[frameToSend.length - 1] = crc[1];
		
		byte[] rad = Radian.byteArrayToRadian(frameToSend);	//transform frame to Radian	
		
		//send wake up
		for (int i = 0; i < 10; i++) {
			rfModule.sendPacket(preamble, 64);
		}
		
		//send request to MIU
		rfModule.sendPacket(rad, rad.length);
		
		rfModule.writeRegister(CC1101Reg.IOCFG0.getValue(), 0x01);
		rfModule.writeRegister(CC1101Reg.SYNC0.getValue(), 0x00);
		rfModule.writeRegister(CC1101Reg.SYNC1.getValue(), 0x00);
		
		//Start reception
		rfModule.sendCommand(CC1101Command.SRX);
		
		Thread.sleep(1000);
		if(rfModule.gdo0.isLow()) throw new IOException("timeout");  //wait until a packet is received
		
		int length = rfModule.readRegister(CC1101Reg.RXBYTES.getValue());
		if(length == 0) throw new IOException("SPI communication problem");
			
		byte[] received = new byte[length];
		rfModule.readBurstRegister(CC1101Reg.RXFIFO.getValue(), received, length);
		
		return received;
	}

}
